package in.muton.edushare.pages.coursepages;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.cayenne.PersistenceState;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.internal.HtmlHeaderContainer;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.dao.AttendanceRegisterDAO;
import com.edushare.common.dao.UsersDAO;
import com.edushare.common.exceptions.EduShareRuntimeException;
import com.edushare.common.orm.CayenneORMInterface;
import com.edushare.common.vo.AttendanceRegister;
import com.edushare.common.vo.Enrolments;
import com.edushare.common.vo.Users;

public class Attendance extends CourseBase {

	private final Date currentDate;
	
	public Attendance(PageParameters params) {
		super(params);
		this.currentDate = new Date();
		//History
		final WebMarkupContainer wmc = new WebMarkupContainer("hishis");
		wmc.setOutputMarkupPlaceholderTag(true);
		add(wmc);
		wmc.setVisible(false);
//		List<AttendanceRegister> ars = AttendanceRegisterD
		final List<String> dates = Arrays.asList(new String[]{"01","02","03","04","05","06","07","08"});
		add(new AjaxLink<Void>("hishisLink"){

			private static final long serialVersionUID = 4418875165803740784L;
			@Override
			public void onClick(AjaxRequestTarget target) {
				final List<AttendanceRegister> regs = new AttendanceRegisterDAO(getSessionORMInterface()).getMonthlyAttendanceList(new Date(), Attendance.super.getCourseInstance().getObject());
				if(!wmc.isVisible()){
					target.addComponent(wmc.setVisible(true));
					wmc.addOrReplace(
					new ListView<AttendanceRegister>("hislis", regs){
						private static final long serialVersionUID = -7754941170288367073L;
						@Override
						protected void populateItem(ListItem<AttendanceRegister> item) {
							    Calendar c = Calendar.getInstance();
							    c.setTime(item.getModelObject().getAttdDate());
								item.add(new Label("hisDate", ""+c.get(Calendar.DAY_OF_MONTH)));
								item.add(new Label("hisName", item.getModelObject().getName()));
						}
						
					});
				}
				else{
					target.addComponent(wmc.setVisible(false));
				}
			}
		});
		
		
		final WebMarkupContainer testme = new WebMarkupContainer("testme");
		add(testme);
		testme.setOutputMarkupId(true);	
		
		//list
		add(new AttendancePanel("attdlst", this, new Date()));
		
	}

	private List<TempAttendace> filterValid(List<Enrolments> enrolmentList) {
		ArrayList<TempAttendace> al = new ArrayList<TempAttendace>();
		for(Enrolments e: enrolmentList)
			if(e.getEnrolmentType()==Enrolments.STUDENT && e.getStatus()==Enrolments.ENROLLED){
				TempAttendace ta = new TempAttendace();
				ta.setUser(e.getUser());
				ta.setAttendance(false);
				al.add(ta);
			}
		
		return al;
	}

	
	
	@Override
	protected String getActivePage(PageParameters params) {
		return "attendance";
	}

	@Override
	public String getPageTitle() {
		return super.getCourse().getObject().getCourseName() + " Attendance";
	}
	
	//Attendance List
	public class AttendancePanel extends Fragment{
		private static final long serialVersionUID = -4153834120130617242L;
		final HiddenField<String> hdnDate;
		public AttendancePanel(String id, MarkupContainer markupProvider, Date date) {
			super(id, "attdPanel", markupProvider);
			final AttendanceRegister regvo = new AttendanceRegister();
			Form<Void> form = new Form<Void>("attdnForm");
			form.add(hdnDate = new HiddenField<String>("attdnOn", new IModel<String>(){

				private static final long serialVersionUID = -3044413004165390012L;

				public String getObject() {
					if(regvo.getAttdDate()==null)regvo.setAttdDate(new Date());
					return new SimpleDateFormat("MM/dd/yyyy").format(regvo.getAttdDate());
				}

				public void setObject(String date) {
					try {
						System.out.println("Date: "+ date);
						regvo.setAttdDate(new SimpleDateFormat("MM/dd/yyyy").parse(date));
					} catch (ParseException e) {
						throw new EduShareRuntimeException();
					}
				}

				public void detach() {}
				}));
			
			hdnDate.setOutputMarkupId(true);
			form.add(new TextField<String>("attdnName", new PropertyModel<String>(regvo, "name")));
			
			final List<TempAttendace> stdAtt = filterValid(getCourseInstance().getObject().getEnrolmentList());
			form.add(new ListView<TempAttendace>("stdsRow", stdAtt) {

				private static final long serialVersionUID = 1L;

				@Override
				protected void populateItem(ListItem<TempAttendace> item) {
					item.add(new CheckBox("isPresent", new PropertyModel<Boolean>(item.getModel(), "attendance")));
					item.add(new Label("attdName", new PropertyModel<String>(item.getModel(), "user.userName")));
					item.add(new AjaxEventBehavior("onClick"){
						private static final long serialVersionUID = -938323037775390783L;

						@Override
						protected void onEvent(AjaxRequestTarget target) {
							
						}
						
					});
				}
				
			});
			
			form.add(new Button("attdSubm"){
				private static final long serialVersionUID = -2166511896141947133L;

				@Override
				public void onSubmit() {
					((CayenneORMInterface)getSessionORMInterface()).getDataContext().registerNewObject(regvo);
					regvo.setCourseInstance(getCourseInstance().getObject());
					getSessionORMInterface().commitAllChanges();
					for(TempAttendace a:stdAtt){
						com.edushare.common.vo.Attendance avo = ((CayenneORMInterface)getSessionORMInterface()).getDataContext().newObject(com.edushare.common.vo.Attendance.class);
						avo.setAttdDate(regvo.getAttdDate());
						avo.setAttendanceRegister(regvo);
						avo.setCourseInstance(getCourseInstance().getObject());
						avo.setPresent(a.getAttendance());
						System.out.println("Users: "+a.getUser());
						avo.setUser(a.getUser());
					}
					getSessionORMInterface().commitAllChanges();
				}
			});
			add(form);
		}
		
		
		@Override
		public void renderHead(HtmlHeaderContainer container) {
				String javascript =
						"$('#fillAtt').datepicker({"+
									 "maxDate: new Date(),"+
									   "onSelect: function(date){"+
											"$('#attdRun').show();"+
											"$('#attdDate').text(date);"+
											"$('#"+this.hdnDate.getMarkupId()+"').val(date);"+
											"$('.cb input').show();"+
											"$(this).hide();"+
											"$('#fillAtt').next().attr('disabled', true);"+
									    "}"+
									 "});"+
						"$('#fillAtt').next().click(function(e){e.preventDefault();$(this).prev().toggle();return false;});"+
						"$('#attdCan').click(function(e){"+
										"e.preventDefault();"+
										"$('#fillAtt').next().attr('disabled', false);"+
										"$('.cb input').attr('checked', false).hide();"+
										"$('#attdRun').hide();"+
									"});"+
						"$('#newCal').click(function(e){"+
						"e.preventDefault();"+
						"$(this).prev('div').toggle();"+
						"return false;"+
						"});";
				container.getHeaderResponse().renderOnDomReadyJavascript(javascript);
		}
		
	}
	
	//PlaceHolder for attendance
	public class TempAttendace implements Serializable{
		private static final long serialVersionUID = -1064676696738140202L;
		public Users user;
		public int userId;
		public Users getUser() {
			if(this.user.getPersistenceState() == PersistenceState.HOLLOW || (this.user==null && this.userId != 0))
				this.user = new UsersDAO(getSessionORMInterface()).getUserByPk(userId);
			return user;
		}
		public void setUser(Users user) {
			this.user = user;
			this.userId = user.getUserId();
		}
		public boolean getAttendance() {
			return attendance;
		}
		public void setAttendance(boolean attendance) {
			this.attendance = attendance;
		}
		public boolean attendance;
		
	}

}
